/*
 * lineplot.h
 *
 *  Created on: 22.3.2010
 *      Author: aahv
 */

#ifndef LINEPLOT_H
#define LINEPLOT_H

#include "lineplotdata.h"

#include <qmath.h>

#include <QWidget>

#include <QDebug>

class LinePlot : public QWidget
{
public:
    LinePlot(QWidget* parent=0);

    void setData(LinePlotData* data);

    void setXAxisMajorTickFrequency(int freq);

protected:
    void resizeEvent(QResizeEvent* event);
    void paintEvent(QPaintEvent* event);

    void drawAxis(QPainter& painter) const;
    void drawData(QPainter& painter) const;

    void calculateGeometry();
    
private:
    int xCoordinateForTick(int index) const;
    int yCoordinateForTick(int index) const;
    int yCoordinateForValue(int index) const;
    int yValueForTick(int index) const;

    int yAxisMinValue() const {
        if (zeroVisible)
            return 0;

        int diff = data->getMaxValue() - data->getMinValue();
        if (diff < yAxisTickCount)
            return 0;

        int val = diff / (yAxisTickCount - 1);
        int p = qLn(val) / qLn(10);
        int t = qPow(10, p);
        int minval = (data->getMinValue() % t == 0? data->getMinValue(): (data->getMinValue() / t) * t);

        return minval;
    }
    int yAxisValueDiff() const {
        int minValue = (zeroVisible? 0: data->getMinValue());
        int diff = data->getMaxValue() - minValue;
        if (diff < yAxisTickCount)
            return yAxisTickCount - 1;
        int val = diff / (yAxisTickCount - 1);
        int p = qLn(val) / qLn(10);
        int t = qPow(10, p);
        int tick = (val % t == 0? val: (val / t + 1) * t);
        int m = (data->getMaxValue() % tick == 0? data->getMaxValue(): (data->getMaxValue() / tick + 1) * tick);
        return qMax((yAxisTickCount - 1), m - yAxisMinValue());
    }

private:
    LinePlotData* data;

    QFont font;
    QRect yAxisLabelMetrics;
    QRect xAxisLabelMetrics;

    QPoint origo;
    QPoint xAxisEnd;
    QPoint yAxisEnd;

    int xAxisMajorTickFreq;
    int yAxisTickCount;

    bool zeroVisible;
    bool gridVisible;

};

#endif // LINEPLOT_H
